/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hashChunk;
import common.global;
import java.io.*;  
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
 *
 * @author DongVan
 */
public class SplitFile {
    int FRG_FSIZE=0;  
      
    public String splitFile(File source) throws NoSuchAlgorithmException
    {  
        String torent = null;
        ArrayList<String> listSHA1 = new ArrayList<String>();
        MessageDigest md = MessageDigest.getInstance("SHA1");
        FRG_FSIZE = 1024*512;//do dai cua 1 chunk
        int noFile = (int)source.length()/FRG_FSIZE;//So luong chunks cua mot file
        if((int)source.length()%FRG_FSIZE != 0){
            noFile++;
        }
        
        File[] fileFragments = new File[noFile];  
        String[] frgfName = new String[noFile];  
            try{      
                String sourceFName = source.getName();  
                long sourceFSize = source.length();  
                FileInputStream fis = new FileInputStream(source);
                String str = sourceFName.replace("_", " ");
                int flag = 0;
                File folder = null;
                int index = 0;
                String folderName = "C:\\BittorentShared\\" +sourceFName.replace(".", global.separatorBittorentTxt);
                while(flag == 0)
                {
                    folder = new File(folderName);
                    if(!folder.exists()){
                        folder.mkdir();
                        flag = 1;
                    }
                    else{
                        index++;
                        folderName+= "_"+index;
                    }   
                }
                String test = sourceFName.replace("_", " ");
                BufferedWriter out = new BufferedWriter(new FileWriter("src\\FolderTorrentFile\\" + test.replace(".", "_")+"_torent.txt"));
                String line = "";
                for (int i = 1; i <= noFile; i++) { 
                    
                    frgfName[i-1] =folder.getPath()+"\\"+String.valueOf(i)+global.separatorBittorentTxt +sourceFName + global.separatorBittorentTxt+".chunk";  
                    fileFragments[i-1] = new File(frgfName[i-1]);  
                    FileOutputStream fos = new FileOutputStream(fileFragments[i - 1]);  
                    byte[] data = new byte[FRG_FSIZE];  
                    int count = fis.read(data);  
                    md.update(data, 0, count);
                    byte[] mdbytes = md.digest();
                    StringBuffer sb = new StringBuffer("");
                    for (int j = 0; j < mdbytes.length; j++) {
                        sb.append(Integer.toString((mdbytes[j] & 0xff) + 0x100, 16).substring(1));
                    }
                    listSHA1.add(sb.toString());
                    fos.write(data);  
                    fos.close();  
                    
                    //String frgFileInfo = new String(frgfName[i-1] + "," + String.valueOf(FRG_FSIZE)); 
                    line = String.valueOf(i)+ global.separatorBittorentTxt + sourceFName + global.separatorBittorentTxt + sb.toString() +global.separatorBittorentTxt +"chunk"  ; 
                    out.write(line);
                    out.newLine();
                }  
                    
                out.close();
                torent = "src\\FolderTorrentFile\\" + sourceFName+".torent.txt";
                
                //int debug = 1;
               } catch (Exception e) {       
                   System.out.println("Error in Splitting" + e);  
                   JOptionPane.showMessageDialog(null, "Error in Splitting File \n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);  
                   return null;  
               }  
        return torent;  
  }  
  
    public File mergeFiles(String pathContainChunks,String destinationStoreFileDownloaded, String fileName) {  
        try {  
            File folder = new File(pathContainChunks);
            File[] files = folder.listFiles();    
            File outFile = new File(destinationStoreFileDownloaded+"\\"+fileName);   
            FileOutputStream fileOS = new FileOutputStream(outFile);  
            for (int i = 0; i < files.length; i++) {  
                FileInputStream fileIS = new FileInputStream(files[i]);  
                byte[] data = new byte[(int) files[i].length()];  
                int count = fileIS.read(data);  
                fileOS.write(data);  
                fileIS.close();   
            }  
            fileOS.close();  
            return outFile;  
        } catch (Exception e) {  
            JOptionPane.showMessageDialog(null, "Error in Merge File \n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);  
        }  
        return null;  
    }
}
